package com.hr.mes.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.hr.mes.dto.Page;
import com.hr.mes.entity.Menu;
import com.hr.mes.mapper.MenuMapper;
import com.hr.mes.service.MenuService;
import com.hr.mes.utils.PageUtil;
import com.hr.mes.vo.MenuVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Service
@Transactional
public class MenuServiceImpl implements MenuService {

    @Autowired
    private MenuMapper menuMapper;

    @Override
    public void addMenu(Menu menu) {
        menuMapper.addMenu(menu);
    }

    @Override
    public void deleteMenu(Integer menuId) {
        menuMapper.deleteMenu(menuId);
    }

    @Override
    public void updateMenu(Menu menu) {
        menuMapper.updateMenu(menu);
    }

    @Override
    public Menu getMenu(Integer menuId) {
        return menuMapper.getMenu(menuId);
    }

    @Override
    public Page<Menu> getMenuList(Integer pageNo, Integer pageSize) {
        List<Menu> menuList = menuMapper.getMenuList();
        PageHelper.startPage(pageNo, pageSize);
        PageInfo<Menu> pageInfo = new PageInfo<>(menuList);
        Page<Menu> page = PageUtil.ConvertPageInfoToPage(pageInfo);
        PageHelper.clearPage();
        return page;
    }

    @Override
    public List<Menu> getChildren(Integer menuId) {
        return menuMapper.getChildren(menuId);
    }

    @Override
    public List<MenuVO> getAvailableMenuList() {
        List<Menu> menuList = menuMapper.getMenuList();
        menuList = menuList.stream().filter(menu -> menu.getStatus() == 1).collect(Collectors.toList());
        List<MenuVO> menuVOList = convertMenuListToMenuVOList(menuList);
        return menuVOList;
    }

    private List<MenuVO> convertMenuListToMenuVOList(List<Menu> menuList){
        ArrayList<MenuVO> menuVOList = new ArrayList<>();
        if(!CollectionUtils.isEmpty(menuList)){
            for (Menu menu : menuList){
                MenuVO menuVO = new MenuVO();
                menuVO.setId(menu.getMenuId());
                menuVO.setTitle(menu.getTitle());
                menuVO.setIcon(menu.getIcon());
                menuVO.setType(menu.getType());
                menuVO.setHref(menu.getHref());
                List<Menu> children = menu.getChildren();
                if(!CollectionUtils.isEmpty((children))){
                    List<MenuVO> childrenMenuVO = convertMenuListToMenuVOList(children);
                    menuVO.setChildren(childrenMenuVO);
                }
                menuVOList.add(menuVO);
            }
        }
        return menuVOList;
    }
}
